<?php

define( "CONFIG_DIR", realpath( dirname( __FILE__ ) . "/../../Config" ) );


require_once dirname( __FILE__ ) . "/../PokaYoke/PokaYoke.class.php";


// Exceptions
require_once "Exceptions/ConfigFileNotFound.class.php";
require_once "Exceptions/ConfigCacheNotFound.class.php";


class Config extends PokaYoke
{
	private $_cachedFile;
	private $_configFile;

	
	public function __construct( $file )
	{
    	parent::__construct( array(), TRUE );

		$this->_configFile = CONFIG_DIR . "/" . $file;
		$this->_cachedFile = CONFIG_DIR . "/"
		. str_replace( ".", "-", substr( $file, 0, strrpos( $file, "." ) ) )
		. "_" . md5( $file );

		// Check if Configuration File exists
		if ( ! file_exists( $this->_configFile ) ) {
            throw new ConfigFileNotFound(
				"Configuration file [ " . $this->_configFile . " ] does not exist."
			);
		}

		// Check if Cache exists or is valid
		$cachedFileExists = file_exists( $this->_cachedFile );

    	if ( ( ! $cachedFileExists ) || ( $cachedFileExists && ( filemtime( $this->_configFile ) >  filemtime( $this->_cachedFile ) ) ) ) {
        	// Must (re)create cache file
			$this->createCache();
		}

		// Check if Configuration could be cached
		if ( file_exists( $this->_cachedFile ) ) {
        	include $this->_cachedFile;
		} else {
			throw new ConfigCacheNotFound(
				"Configuration Cache file [ " . $this->_cachedFile . " ] does not exist."
			);
		}
	}
	
	
	public function getConfigFile()
	{
		return $this->_configFile;
	}
	
	
	public function getCachedFile()
	{
		return $this->_cachedFile;
	}
	
	
	private function createCache()
	{
		$lines = file( $this->_configFile, FILE_SKIP_EMPTY_LINES );

		// Open cache file in write mode
		$fp = fopen( $this->_cachedFile, "w+" );

		// Lock file for write
		if ( flock( $fp, LOCK_EX ) ) {
			fwrite( $fp, "<?php\r\n\r\n// Configuration AutoGenerated Cache File\r\n" );

			for ( $i = 0, $len = count( $lines ); $i < $len; $i++ ) {
				// offset=value
				$item = explode( "=", $lines[$i]);

				// Write in cache file: $this->set("offset", "value");
				if ( strlen( trim( $lines[$i] ) ) > 0 && count( $item ) > 0 ) {
            		fwrite( $fp, "\$this->set( \"" . trim($item[0]) . "\", \"" . trim($item[1]) . "\" );\r\n" );
				}
			}
			
			fwrite( $fp, "\r\n?>" );
		}
		
		// Release lock and close file
		flock( $fp, LOCK_UN );
		fclose( $fp );
	}
}

?>